<template>
  <div>
    <upload-excel :on-success="onSuccess"></upload-excel>
  </div>
</template>

<script>
import { importEmployee } from '@/api/employees'
export default {
  name: 'Import',
  components: {},
  props: {},
  data() {
    return {}
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    async onSuccess({ header, results }) {
      // 如果是导入员工
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      // const arr = results.map(item => {
      //   const userInfo = {}
      //   Object.keys(item).forEach(key => {
      //     userInfo[userRelations[key]] = item[key]
      //   })
      //   return userInfo
      // })
      // const arr = []
      // results.forEach(o => {
      //   const userInfo = {}
      //   console.log(Object.keys(o))
      //   Object.keys(o).forEach(key => {
      //     userInfo[userRelations[key]] = o[key]
      //   })
      //   arr.push(userInfo)
      // })
      // console.log(arr)
      results.forEach(item => {
        for (const key in item) {
          if (key === '入职日期' || key === '转正日期') {
            item[userRelations[key]] = new Date(this.formatDate(item[key]), '/')
          }
          delete item[key]
        }
      })
      // console.log(results)
      await importEmployee(results) // 调用导入接口
      this.$message.success('导入Excel成功') // 提示成功
      this.$router.back()
    },
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style lang="less" scoped>
</style>
